<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JSONP 客户端示例</title>
</head>

<body>
    <button id="fetchDataButton">获取数据</button>
    <div id="result"></div>

    <script>
        document.getElementById('fetchDataButton').addEventListener('click', function () {
            // 生成唯一的回调函数名
            const callbackName = `jsonpCallback_${Date.now()}`;

            // 定义回调函数
            window[callbackName] = function (data) {
                const resultDiv = document.getElementById('result');
                resultDiv.textContent = `服务器返回的消息: ${data.message}`;

                // 回调执行后删除全局函数
                delete window[callbackName];
            };

            // 创建 URL 对象
            const url = new URL('http://localhost:3000//jsonp');
            // 添加 callback 参数
            url.searchParams.set('callback', callbackName);

            // 创建 script 标签
            const script = document.createElement('script');
            script.src = url.href;

            // 处理脚本加载错误
            script.onerror = function () {
                const resultDiv = document.getElementById('result');
                resultDiv.textContent = '请求出错，请检查网络或服务器状态。';
                // 删除全局函数
                delete window[callbackName];
            };

            // 脚本加载完成后移除
            script.onload = function () {
                document.body.removeChild(script);
            };

            document.body.appendChild(script);
        });
    </script>
</body>

</html>    